package com.ruoyi.quartz.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.quartz.domain.Dept;
import com.ruoyi.quartz.domain.User;
import com.ruoyi.quartz.mapper.DeptMapper;
import com.ruoyi.quartz.service.IDeptService;
import com.ruoyi.quartz.service.ISysDingTaskService;
import com.ruoyi.quartz.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Service
public class SysDingTaskServiceImpl implements ISysDingTaskService {

    private static final Logger logger = LoggerFactory.getLogger(SysDingTaskServiceImpl.class);

    // 钉钉
    private static final String APP_KEY = "dinguwihvg9l52h7w41t";
    private static final String APP_SECRET = "thnQvJALi_O43zuv6ItjXUFRBZAW7XxhnORZgxtin1vk8msC2bfkMuLMrZMvnOHK";

    @Autowired
    public IDeptService deptService;

    @Autowired
    public IUserService userService;

    @Override
    public void getMembersData() {
        String accessToken = null;

        try {
            accessToken = getAccessToken4DD();
        }catch (Exception e) {
            e.printStackTrace();
        }
        if(accessToken!=null){
            try {
                List<String> result = getDepartmentIds(accessToken);
                getDepartmentMembers(accessToken,result);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String getAccessToken4DD() throws Exception {
        String url = "https://oapi.dingtalk.com/gettoken?appkey=" + APP_KEY + "&appsecret=" + APP_SECRET;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        String jsonResponse = response.toString();
        org.json.JSONObject jsonObject = new org.json.JSONObject(jsonResponse);
        return jsonObject.getString("access_token");
    }

    public List<String> getDepartmentIds(String accessToken) throws Exception {
        String url = String.format("https://oapi.dingtalk.com/department/list?access_token=%s", accessToken);
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        String json = response.toString();
        org.json.JSONObject jsonObject = new org.json.JSONObject(json);
        org.json.JSONArray department = jsonObject.getJSONArray("department");
        List<String> departmentIds = new ArrayList<>();
        if(department!=null){
            if(department.length()>0){
                for(int i=0;i<department.length();i++){
                    if(department.getJSONObject(i).getInt("id")!=1){
                        if(!department.getJSONObject(i).getString("name").equalsIgnoreCase("马福艳")){
                            Dept initDept = deptService.selectSysDeptByDeptId((long)department.getJSONObject(i).getInt("id"));
                            if(initDept!=null){
                                initDept.setDeptName(department.getJSONObject(i).getString("name"));
                                initDept.setParentId((long)department.getJSONObject(i).getInt("parentid"));
                                deptService.updateSysDept(initDept);
                            }else{
                                Dept dept = new Dept();
                                dept.setDeptId((long)department.getJSONObject(i).getInt("id"));
                                dept.setDeptName(department.getJSONObject(i).getString("name"));
                                dept.setParentId((long)department.getJSONObject(i).getInt("parentid"));
                                dept.setStatus("0");
                                dept.setDelFlag("0");
                                deptService.insertSysDept(dept);
                            }
                        }
                    }
                    if(!department.getJSONObject(i).getString("name").equalsIgnoreCase("马福艳")){
                        departmentIds.add(department.getJSONObject(i).getInt("id")+"");
                    }
                }
            }
        }
        return departmentIds;
    }

    public void getDepartmentMembers(String accessToken, List<String> ids) throws Exception {
        if(ids.size()>0){
            for(int i=0;i<ids.size();i++){
                String url = String.format("https://oapi.dingtalk.com/user/list?access_token=%s&department_id=%s&lang=zh_CN", accessToken, ids.get(i));
                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                con.setRequestMethod("GET");

                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                String json = response.toString();
                org.json.JSONObject jsonObject = new org.json.JSONObject(json);
                org.json.JSONArray userlist = jsonObject.getJSONArray("userlist");
                if(userlist.length()>0){
                    for(int j=0;j<userlist.length();j++){
                        User initUser = userService.selectSysUserByUserCode(userlist.getJSONObject(j).getString("userid"));
                        if(initUser!=null){
                            initUser.setAvatar(userlist.getJSONObject(j).getString("avatar"));
                            userService.updateSysUser(initUser);
                        }else{
                            User user = new User();
                            user.setDeptId(Long.parseLong(ids.get(i)));
                            user.setUserName(userlist.getJSONObject(j).getString("name"));
                            user.setNickName(userlist.getJSONObject(j).getString("name"));
                            user.setAvatar(userlist.getJSONObject(j).getString("avatar"));
                            user.setUserType("00");
                            user.setStatus("0");
                            user.setDelFlag("0");
                            user.setUserCode(userlist.getJSONObject(j).getString("userid"));
                            user.setPassword("$2a$10$Pkz1ElBBGk4Dq0JM82Jl0urvypeCdg305iYWoRvfWn33B1C2XM2JO");
                            userService.insertSysUser(user);
                        }
                    }
                }
            }
        }
    }
}
